<?php
/*由脚本生成 powerBy--Reer*/

namespace app\common\manage;

use app\common\bean\ConfigBean;
use app\common\bean\ListMap;
use app\common\enum\ConfigTypeEnum;
use app\common\exception\MyException;
use app\common\model\ConfigModel;

class ConfigManage
{
    static $_self = null;
    public static function getInstance(){
        if(empty(self::$_self)){
            self::$_self = new ConfigManage();
        }
        return self::$_self;
    }

    /** 获取系统配置
     * @param array $where
     * @return array|bool|false
     * @throws \Exception
     */
    public function getConfig($where = []){
        $result = ConfigModel::getInstance()->selectData($where,true);
        $result !== false ?: MyException::throwMyException("获取失败");
        return $result;
    }

    /** 更新系统配置
     * @param ListMap $listMap
     * @param int $storeId
     * @return bool
     * @throws \Exception
     */
    public function editConfig(ListMap $listMap,$storeId = 0){
        foreach ($listMap->getData() as $key => $value){
            $configBean = new ConfigBean;
            $result = ConfigModel::getInstance()->selectData([ConfigBean::$configKey => $key]);
            if($result){
                $configBean->setData($result);
                switch ($configBean->getType()){
                    case ConfigTypeEnum::TEXTEARE:
                    case ConfigTypeEnum::INPUT:
                        ConfigModel::getInstance()->updatedData(array(ConfigBean::$configKey => $key,ConfigBean::$storeId => $storeId),array(ConfigBean::$value => $value));
                        break;
                    case ConfigTypeEnum::IMG:
                        ConfigModel::getInstance()->updatedData(array(ConfigBean::$configKey => $key,ConfigBean::$storeId => $storeId),array(ConfigBean::$value => json_encode($value)));
                        break;
                }
            }

        }
        return true;
    }

    /** 组装获取select数据
     * @param $modelList
     * @param $fieldId
     * @param $fieldName
     * @return array
     */
    public function modelToInputSelect($modelList,$fieldId,$fieldName){
        $select = array();
        foreach ($modelList as $value){
            $select[$value[$fieldId]] = $value[$fieldName];
        }
        return $select;
    }

    /** 获取全部系统配置
     * @return array|bool|false
     * @throws \Exception
     */
    public function getAllConfig(){
        $result = ConfigModel::getInstance()->selectData(array(),true);
        $result ?: MyException::throwMyException("获取失败");
        return $result;
    }
}